package com.yzf.zyfverifycode.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.yzf.zyfverifycode.Constants;
import com.yzf.zyfverifycode.SimUtils;

import org.json.JSONException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.MODE_PRIVATE;
import static com.yzf.zyfverifycode.Constants.TAG;

/**
 * 项目名称：FoldingVerifyCode
 * 类描述：验证工具类
 * 创建人：Administrator
 * 创建时间：2019年10月1日
 */
public class Utils {

    private static List<String> ignorNoList = new ArrayList<>();

    public static String getBankNameByNum(String str) {
        switch (str) {
            case "95588":
                return "中国工商银行";
            case "95599":
                return "中国农业银行";
            case "95533":
                return "中国建设银行";
            case "95568":
                return "中国民生银行";
            case "106905695568":
                return "中国民生银行";
            case "95528":
                return "上海浦东发展银行";
            case "95508":
                return "广发银行";
            case "95511":
                return "平安银行";
            case "8695511":
                return "平安银行";
            case "95577":
                return "华夏银行";
            case "95561":
                return "兴业银行";
            case "1069195561":
                return "兴业银行";
            case "1069295561":
                return "兴业银行";
            case "兴业银行":
                return "兴业银行";
            case "95566":
                return "中国银行";
            case "95580":
                return "浙商银行";
            case "1069013396299":
                return "桂林银行";
            case "桂林银行":
                return "桂林银行";
            case "106980096289":
                return "柳州银行";
            case "柳州银行":
                return "柳州银行";
            case "106980096288":
                return "北部湾银行";
            case "96568":
                return "湖北农商银行";
            case "1069049996568":
                return "湖北农商银行";
            case "95595":
                return "中国光大银行";
        }
        return str;
    }

    public static String getTel(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return "";
        }
        String tel = tm.getLine1Number();//手机号码
        Log.d(TAG, "getTel = " + tel);
        return tel;
    }

    /**
     * @功能: BCD码转为10进制串(阿拉伯数据)
     * @参数: BCD码
     * @结果: 10进制串
     */
    public static String bcd2Str(byte[] bytes) {
        StringBuffer temp = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            temp.append((byte) ((bytes[i] & 0xf0) >>> 4));
            temp.append((byte) (bytes[i] & 0x0f));
        }
        return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp
                .toString().substring(1) : temp.toString();
    }

    public static String getValueFromSP(Context context, String name, String key) {
        Log.d(TAG, "getValueFromSP name = " + name + " key " + key);
        String result = getSharedPreferences(context, name).getString(key, "");
        return result;
    }

    private static SharedPreferences getSharedPreferences(Context context, String name) {
        SharedPreferences preferences = context.getSharedPreferences(name, MODE_PRIVATE);
        Log.d(TAG, "getValueFromSP name = " + name + " size " + preferences.getAll().size());
        return preferences;
    }

    public static boolean save2SP(Context context, String name, String key, String value) {
        Log.d(TAG, "save2SP name = " + name + " key " + key + " value " + value);
        SharedPreferences preferences = getSharedPreferences(context, name);
        SharedPreferences.Editor edit = preferences.edit();
        edit.putString(key, value);
        return edit.commit();
    }

    public static boolean delFromSP(Context context, String name, String key) {
        SharedPreferences preferences = getSharedPreferences(context, name);
        SharedPreferences.Editor edit = preferences.edit();
        return edit.remove(key).commit();
    }

    public static String getUrl(Context context) {
        String urlsp = getValueFromSP(context, Constants.HTTPS_URL, Constants.HTTPS_URL_KEY);
        return urlsp;
    }

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 从短信字符窜提取验证码
     *
     * @param body 短信内容
     * @return 接取出来的验证码
     */
    public static String getyzm(String body, String NO) {
        Log.d(TAG, "getyzm enter ");
        // 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的六位数字字母组合
        // (?<![a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数字
        // (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现

        if (isNeedSend(NO) || body.contains(Constants.MSG_ZHUANZHANG) || body.contains(Constants.MSG_HUIKUAN) || body.contains(Constants.MSG_LOGIN)) {
            Pattern p1 = Pattern
                    .compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + 6 + "})(?![a-zA-Z0-9])");
            Log.e(TAG, "getyzm body=== " + body);
            Matcher m1 = p1.matcher(body);
            if (m1.find()) {
                Log.e(TAG, "onReceive: " + m1.group(0));
                return m1.group(0);
            }
            Log.e(TAG, "getyzm body=== " + "find()==false");
//            Pattern   = Pattern
//                    .compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + 4 + "})(?![a-zA-Z0-9])");
//            Matcher m2 = p2.matcher(body);
//            if (m2.find()) {
//                Log.e(TAG, "onReceive: " + m2.group(0));
//                return m2.group(0);
//            }
        } else {
            return "";
        }
        return "";
    }

    public static boolean isNeedSend(String NO) {
//        // 工商银行
//        ignorNoList.add(Constants.ICBNO);
//        ignorNoList.add(Constants.ICBNOPLUS);
//        // 农业银行
//        ignorNoList.add(Constants.ABCNO);
//        ignorNoList.add(Constants.ABCNOPLUS);
        // 建设银行
        ignorNoList.add(Constants.CCBNO);
        ignorNoList.add(Constants.CCBNOPLUS);
        // 民生银行
        ignorNoList.add(Constants.CMBCNO);
        ignorNoList.add(Constants.CMBCNOPLUS);
        // 浦发银行
        ignorNoList.add(Constants.SPDBNO);
        ignorNoList.add(Constants.SPDBNOPLUS);
        // 广发银行
        ignorNoList.add(Constants.CGBNO);
        ignorNoList.add(Constants.CGBNOPLUS);
        // 平安银行
        ignorNoList.add(Constants.PANO);
        ignorNoList.add(Constants.PANOPLUS);
        // 华夏银行
        ignorNoList.add(Constants.HXNO);
        ignorNoList.add(Constants.HXNOPLUS);
        // 兴业银行
        ignorNoList.add(Constants.CIBNO);
        ignorNoList.add(Constants.CIBNOPLUS);
        ignorNoList.add(Constants.CIBNOPLUS1);
        ignorNoList.add(Constants.CIBNOPLUS2);
        ignorNoList.add("兴业银行");
        // 中国银行
        ignorNoList.add(Constants.BOCBNO);
        ignorNoList.add(Constants.BOCBNOPLUS);
//        // 浙商银行
//        ignorNoList.add(Constants.ZSBCNO);
//        ignorNoList.add(Constants.ZSBCNOPLUS);
        // 桂林银行
        ignorNoList.add(Constants.GLBNO);
        ignorNoList.add(Constants.GLBNOPLUS);
        ignorNoList.add("桂林银行");
        // 柳州银行
        ignorNoList.add("柳州银行");
//        // 北部湾银行
//        ignorNoList.add(Constants.BBWBCNO);
//        ignorNoList.add(Constants.BBWBCNOPLUS);
        // 中国光大银行
        ignorNoList.add(Constants.CEBCNO);
        ignorNoList.add(Constants.CEBCNOPLUS);
        // 湖北农信
        ignorNoList.add(Constants.HBNXNO);
        ignorNoList.add(Constants.HBNXNO1);
        ignorNoList.add(Constants.HBNXNOPLUS1);

        if (ignorNoList.contains(NO)) {
            Log.e(TAG, "isNeedSend == " + true);
            return true;
        }
        Log.e(TAG, "isNeedSend == " + false);
        return true;
    }

    public static String getPhoneNoBySubId(Context context, String subId) {
        Log.e(TAG, "getPhoneNoBySubId subId = " + subId);
        if (Constants.simArray.length() == 0) {
            Constants.simArray = SimUtils.getSimInfoBySubscriptionManager(context);
        }
        for (int i = 0; i < Constants.simArray.length(); i++) {
            try {
                String simSubId = Constants.simArray.getJSONObject(i).getString(Constants.SUBID);
                Log.e(TAG, "getPhoneNoBySubId simSubId = " + simSubId);
                if (simSubId.equals(subId)) {
                    Log.e(TAG, "getPhoneNoBySubId find subId success!!!");
                    return getPhoneNoBySerial(context, Constants.simArray.getJSONObject(i).getString(Constants.SUBSCRIBER_ID));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return "";
    }

    public static String getPhoneNoBySortId(Context context, String sortId) {
        Log.e(TAG, "getPhoneNoBySortId sortId = " + sortId);

        if (sortId.equals("1")) {

        }


        if (Constants.simArray.length() == 0) {
            Constants.simArray = SimUtils.getSimInfoBySubscriptionManager(context);
        }
        for (int i = 0; i < Constants.simArray.length(); i++) {
            try {

            } catch (Exception e) {

            }
        }
        return "";
    }

    public static String getPhoneNoBySerial(Context context, String simSerial) {
        return Utils.getValueFromSP(context, Constants.SIMSERIAL_SHARED, simSerial);
    }

    public static String getPhoneNoByIMSI(Context context, String imsi) {
        return Utils.getValueFromSP(context, Constants.SIMIMSI_SHARED, imsi);
    }

    public static void saveSimSerial(Context context, String key, String simSerial) {
        Utils.save2SP(context, Constants.SIMSERIAL_SHARED, key, simSerial);
    }

    public static String getDeviceIdFromSp(Context context, String key) {
        Log.e(TAG, "getDeviceIdFromSp key = " + key);
        if (TextUtils.isEmpty(key)) {
            return "";
        } else {
            return getValueFromSP(context, Constants.LOGIN_SP, key);
        }
    }

    public static String getUUid(Context context) {
        return getIMEI(context) + "_" + getSerialNumber();
    }

    public static String getIMEI(Context context) {
        String imei;
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return "";
            }
            imei = telephonyManager.getSimSerialNumber();
        } catch (Exception e) {
            e.printStackTrace();
            imei = "";
        }
        return imei;
    }

    public static String getSerialNumber() {
        String SerialNumber = android.os.Build.SERIAL;
        if (TextUtils.isEmpty(SerialNumber)) {
            return "";
        }
        return SerialNumber;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    public static void getSession(Context context) {
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(Uri.parse("content://sms/"),
                new String[]{"* from threads--"}, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                Log.e(TAG, "_id = " + cursor.getInt(0));
//                Log.e(TAG, "DATE = " + cursor.getInt(1));
//                Log.e(TAG, "ERROR = " + cursor.getInt(2));
//                Log.e(TAG, "HAS_ATTACHMENT = " + cursor.getInt(3));
//                Log.e(TAG, "MESSAGE_COUNT = " + cursor.getInt(4));
//                Log.e(TAG, "READ = " + cursor.getInt(5));
//                Log.e(TAG, "RECIPIENT_IDS = " + cursor.getInt(6));
//                Log.e(TAG, "SNIPPET = " + cursor.getInt(7));
//                Log.e(TAG, "SNIPPET_CS = " + cursor.getInt(8));
//                Log.e(TAG, "TYPE = " + cursor.getInt(9));
                String info;
                for (int j = 0; j < cursor.getColumnCount(); j++) {
                    info = "getSession name:" + cursor.getColumnName(j) + "=" + cursor.getString(j);
                    Log.e("====>", info);
                }

            } while (cursor.moveToNext());
        }

    }

    public static void readAllMsg(Activity activity) {
        Uri uri = Uri.parse("content://sms/inbox");
        Cursor cur = activity.managedQuery(uri, null, null, null, null);
        if (cur.moveToFirst()) {
            do {
                String info;
                for (int j = 0; j < cur.getColumnCount(); j++) {
                    info = "readAllMsg name:" + cur.getColumnName(j) + "=" + cur.getString(j);
                    Log.e("====>", info);
                }
            } while (cur.moveToNext());
        }
    }

    public static void readAllMsgTest(Context context) {
        ContentResolver cr = context.getContentResolver();
        //                        短信内容提供者的主机名
        Cursor cursor = cr.query(Uri.parse("content://sms"), null,
                null, null, null);
        while (cursor.moveToNext()) {
            int length = cursor.getColumnCount();
            String info;
            for (int i = 0; i < length; i++) {
                info = "readAllMsgTest name:" + cursor.getColumnName(i) + "=" + cursor.getString(i);
                Log.e("====>", info);
            }
        }
    }

    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return versionCode;
        }
        return versionCode;
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    /**
     * 将Long类型的时间戳转换成String 类型的时间格式，时间格式为：yyyy-MM-dd HH:mm:ss
     */
    public static String stringToLongToDate(String longTime) {
        Date date = new Date(Long.valueOf(longTime));
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sd.format(date);

    }

}
